/**
 * 是否登录
 */
const pathJoin = require('../common-api/data-path')
const { router, libQuery } = require('../../lib/route')
const RxfileWrite = require('rxfile-write')

libQuery((req, res, next, method) => {
  // body 不允许使用get
  const body = req.body || {}
  const username = body.username || ''
  const password = body.password || ''
  const dataPath = pathJoin('login/' + username)
  console.log('login dataPath=', dataPath)

  // 写 cookies 作为接口的登录判断，这个值，看情况
  res.cookie('user', username, { maxAge: 900000, httpOnly: true })

  setLogin(username).then(() => {
    RxfileWrite.write(dataPath, password).then(() => {
      res.send('1')
    }).catch(error => {
      res.renderError('login -< error 2=', error)
    })
  }).catch(error => {
    res.renderError('login -< error 1=', error)
  })
}, '/login', 'text')

module.exports = router

function setLogin(username) {
  const isLoginPath = pathJoin('isLogin/' + username)
  return RxfileWrite.write(isLoginPath, '1')
}